﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace cryptoXL
{
    class Codificacao
    {
        private int FPosCell { get; set; }
        private int FPosChave { get; set; }
        private int FNumLinhas { get; set; }
        private int FNumColunas { get; set; }

        public void Codificar()
        {
            CalcularAreaDaPlanilha();

            string wCell = null;

            for (int i = 1; i <= FNumLinhas; i++)
            {
                for (int j = 1; j <= FNumColunas; j++)
                {
                    wCell = Globals.ThisAddIn.Application.ActiveSheet.Cells(i, j).Formula;

                    wCell = Codificar(wCell);

                    Globals.ThisAddIn.Application.ActiveSheet.Cells(i, j).Formula = wCell;
                }
            }
        }

        private string Codificar(string prStr)
        {
            byte[] wCell = Encoding.ASCII.GetBytes(prStr);
            byte[] wChave = new byte[wCell.Length];

            int i = 0;
            while (i < wChave.Length)
            {
                if (i > Chave.bytes.Length)
                {
                    FPosChave = 0;
                }

                wChave[i] = Chave.bytes[FPosChave];

                i++;
                FPosChave++;
            }

            for (i = 0; i < wCell.Length; i++)
            {
                wCell[i] ^= wChave[i];
                wCell[i] += 32;
            }

            byte[] kkk = {50,255,256,257,300,350,400,512};
            string str = Encoding.ASCII.GetString(kkk);

            prStr = Encoding.ASCII.GetString(wCell);
            
            return prStr;
        }

        private void CalcularAreaDaPlanilha()
        {
            FNumLinhas = Globals.ThisAddIn.Application.ActiveSheet.UsedRange.Rows.Count;
            FNumColunas = Globals.ThisAddIn.Application.ActiveSheet.UsedRange.Columns.Count;
        }
    }
}
